﻿using System;
using System.Linq;
using System.Web.ModelBinding;
using Altairis.FluffyCloud.Data;
using Altairis.FluffyCloud.Security;

namespace Altairis.FluffyCloud.WebCore.Pages.Forum {

    public partial class EditPost : DbPage {

        public TopicPost FormView_GetItem([RouteData]Guid postId) {
            var post = this.DbContext.TopicPosts.SingleOrDefault(x => x.TopicPostId == postId);
            if (post == null) return null;
            if (!post.Topic.EvaluateTopicPermissionsForCurrentUser(TopicAclEntry.OperationEdit)) return null;
            return post;
        }

        public void FormView_UpdateItem([RouteData]Guid postId) {
            TopicPost item = this.FormView_GetItem(postId);
            if (item == null) {
                ModelState.AddModelError("NotFound", "Příspěvek nebyl nalezen nebo k němu nemáte přístup");
                return;
            }
            TryUpdateModel(item);
            if (!ModelState.IsValid) return;
            try {
                this.DbContext.SaveChanges();
                this.Response.RedirectToRoute("ForumDetail", new { id = item.TopicId });
            }
            catch (Exception ex) {
                this.ModelState.AddModelError("SaveError", ex);
            }
        }
    }
}